<template>
  <div>
    <ListTab v-if="!showMobilePage" :show-header="true" />
    <div :class="{'mobile-min-height is-mobile mobile-table':showMobilePage}" class="list-container mengli-container">
      <div class="filter-container">
        <dataDisplay
          v-if="totalCount"
          :data-list="displayData"
          class="mobile-data"
          style="margin-bottom:16px;"
        />
        <template v-if="!showMobilePage">
          <div style="display:flex;align-items:center;position:relative;">
            <FilterSearch :maxlength="10" style="margin-bottom:0;" @postMessage="postMessage" />
            <div class="high-lv" style="color: #406EFF;" @click="showFilterDialog = true">
              <img :src="advancedFilterIcon" alt="">
            </div>
            <div class="high-lv" style="color: #999" @click="resetFilter">
              <img :src="resetFilterIcon" alt="">
            </div>
            <div class="table-list-top table-top-opeator-bar">
              <el-button
                v-if="hasRouteAuth('mengli:list:create')"
                size="small"
                type="primary"
                class="opeator-btn"
                @click="goCreate"
              >
                新建<i class="icon el-icon-plus"/>
              </el-button>
              <div class="opeator-grount">
                <div
                  v-for="item in sortOptions"
                  :key="item.id"
                  :class="{'active': item.id === paramsOptions.sortName}"
                  class="opeator-grount-item"
                  @click="changeSort(item)">
                  {{ item.name }}
                  <div v-if="item.id === paramsOptions.sortName" class="sort-container">
                    <i :class="{'active': paramsOptions.sortType === 1}" class="sort-caret ascending" @click.stop.prevent="changeSortNum(1)"/>
                    <i :class="{'active': paramsOptions.sortType === 0}" class="sort-caret descending" @click.stop.prevent="changeSortNum(0)"/>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div :style="!isActive?{height:'0px',overflow: 'hidden',marginTop:0}:''" style="margin-top:12px;">
            <FilterItem v-for="item in memeOptions" :item="item" :key="item.id" @postMessage="postMessage"/>
          </div>
        </template>
        <div class="content">
          <template v-if="selectValue() && selectValue().length">
            <div class="tag-container">
              <template v-for="(item, index) in selectValue()">
                <el-tag v-if="index <= 2" :key="index" class="filter-tag-group" type="info" disable-transitions>
                  <div class="flex">
                    <span class="input-name">{{ item.name }}：</span>
                    <span class="input-value">{{ item.value }}</span>
                    <div class="filter-tag-close" @click="deleteTag(item, $event)">
                      <i class="el-tag__close el-icon-close" />
                    </div>
                  </div>
                </el-tag>
              </template>
              <span class="select-num-tip" @click="showFilterDialog = true">已选{{ selectValue().length }}项</span>
            </div>
          </template>
        </div>
      </div>
      <div v-loading="loading" class="table-list">
        <template v-if="tableData && tableData.items">
          <el-row>
            <el-col>
              <div v-if="tableData.total < 1" class="empty-container">
                <img :src="emptyImg" alt="">
                <div class="empty-text">暂无数据</div>
              </div>
              <div v-else class="time-wrap">
                <div v-for="(item, index) in tableData.items" :key="index">
                  <div class="time-wrap-item">
                    <div class="label" style="cursor: pointer;" @click="goDetail(item)">
                      {{ item.name }}（{{ item.list.length }}）
                    </div>
                    <div v-if="item.ipName" class="ip-name" @click="goDetail(item)">
                      {{ `${item.ipName?'已关联IP：'+item.ipName:''}` }}
                    </div>
                    <div v-else class="ip-name-btn" @click="toLinkIp(item)">关联IP</div>
                    <div v-if="showMobilePage" class="flex"/>
                    <div v-if="item.list.length > 3" class="expend-btn" @click="switchExpend(item)">{{ item.expend?'收起':'展开' }}</div>
                  </div>
                  <div v-if="item.list.length > 0" id="list-ul" :class="{'hideItem': !item.expend}" class="list-ul">
                    <div
                      v-for="(list, index) in item.list"
                      :key="index"
                      :style="!showMobilePage?{width: itemWidth+'px'}:''"
                      class="list-li"
                      @click="goDetail(item)">
                      <div class="list-img">
                        <img :src="list.url || defaultMengli" :alt="list.name">
                      </div>
                      <div class="list-keyword">
                        <span v-if="list.keyword" style="width: 100%;">
                          “<el-tooltip class="item" placement="top" effect="dark">
                            <div slot="content" style="max-width: 200px;">{{ list.keyword }}</div>
                            <span class="text">{{ list.keyword }}</span>
                          </el-tooltip>”
                        </span>
                      </div>
                    </div>
                  </div>
                  <div v-else class="list-ul" style="justify-content: center;cursor: pointer;" @click="goDetail(item)">暂无表情</div>
                </div>
              </div>
            </el-col>
          </el-row>
          <el-row v-if="showMobilePage" type="flex" justify="left">
            <el-pagination
              v-show="tableData.total > 0"
              :current-page.sync="tableData.page"
              :page-size="tableData.perPage"
              :total="tableData.total"
              :page-sizes="[20, 50, 100, 250, 500]"
              :layout="pageLayout"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </el-row>
          <fixed-pagination>
            <template v-if="showMobilePage">
              <div class="mobile-icon" @click="showFilterDialog = true">
                <el-image :src="mobileIcon" class="img"/>
                <span class="text">筛选</span>
              </div>
              <el-dropdown trigger="click">
                <div class="mobile-icon">
                  <el-image :src="mobileMoreOperateIcon" class="img"/>
                  <span class="text">更多</span>
                </div>
                <el-dropdown-menu slot="dropdown" :hide-on-click="false" style="padding:0;">
                  <el-dropdown-item
                    v-for="item in sortOptions"
                    :key="item.id"
                    @click.native="changeSort(item, true)">
                    <div :class="{'active': item.id === paramsOptions.sortName}" class="dropdown-sort">
                      <div class="name">{{ item.name }}</div>
                      <div class="dropdown-sort-container">
                        <i :class="{'active': paramsOptions.sortType === 1 && item.id === paramsOptions.sortName}" class="icon left el-icon-sort-down"/>
                        <i :class="{'active': paramsOptions.sortType === 0 && item.id === paramsOptions.sortName}" class="icon right el-icon-sort-up"/>
                      </div>
                    </div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <createBtn v-if="hasRouteAuth('mengli:list:create')" mobile-table @click.native="goCreate"/>
            </template>
            <template v-else>
              <div v-if="tableData && tableData.stickersNum" class="title">
                搜索结果共 <span style="color:#333;">{{ tableData.stickersNum || '--' }}</span> 条表情记录
              </div>
              <span style="flex:1;"/>
              <el-pagination
                v-show="tableData.total > 0"
                :current-page.sync="tableData.page"
                :page-size="tableData.perPage"
                :total="tableData.total"
                :page-sizes="[20, 50, 100, 250, 500]"
                layout="total, prev, pager, next, sizes, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
            </template>
          </fixed-pagination>
        </template>
        <div v-else-if="!isInit" class="empty-container">
          <img :src="emptyImg" alt="">
          <div class="empty-text">暂无数据</div>
        </div>
      </div>
    </div>
    <FilterDialog
      ref="filterDialogRef"
      v-model="paramsOptions"
      :drawer-size="760"
      :visible.sync="showFilterDialog"
      @drawerHide="showFilterDialog = false"
      @queryClick="postMessage"
      @queryEmpty="resetFilter"
    >
      <div slot="middleContentPlaceholder">
        <FilterItem v-for="item in memeOptions" :item="item" :key="item.label" :is-reset="resetFilterItem(item.label)" @postMessage="handleFilterItemChange"/>
      </div>
    </FilterDialog>
  </div>

</template>
<script>
// components
import FilterItem from '@/components/Mengli/ModuleComponents/FilterItem.vue';
import FilterSearch from '@/components/Mengli/ModuleComponents/FilterSearch.vue';
import BiaoqingData from '@/components/Mengli/biaoqingData';
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
import ListTab from '@/components/ListTab';
import FilterDialog from '@/components/Tool/module/filterDialog';
import createBtn from '@/components/Common/baseComponent/createBtn';
// utils
import ElMessage from '@/utils/message';
import { hasRouteAuth } from '@/utils/permission';
// filters
import { standardFormatTime } from '@/filters/date';
import { memeOptions } from '@/filters/status';
import mobileTable from '@/mixins/mobileTable';
// api
import { getMengliList, getOptionsIp, getMengliListTotal } from '@/api/mengli';
// img
import emptyImg from '@/assets/empty-table-data.png';
import defaultMengli from '@/assets/mengli/defaultMengli.png';
import icon1 from '@/assets/mengli/downloadNum.png';
import icon2 from '@/assets/mengli/sengNum.png';
import icon3 from '@/assets/mengli/likeNum.png';
import icon4 from '@/assets/mengli/likePrice.png';
import icon5 from '@/assets/mengli/productionTotal.png';
import mobileIcon from '@/assets/mobileIcon/search.png';
import mobileMoreOperateIcon from '@/assets/mobileIcon/moreOperate.png';
import advancedFilterIcon from '@/assets/setting/advancedFilter.png';
import resetFilterIcon from '@/assets/setting/resetFilter.png';

export default {
  components: {
    FilterItem,
    FilterSearch,
    BiaoqingData,
    ListTab,
    dataDisplay,
    FilterDialog, createBtn
  },
  mixins: [mobileTable],
  data() {
    return {
      icon1,
      icon2,
      icon3,
      icon4, advancedFilterIcon, resetFilterIcon,
      icon5, mobileIcon, mobileMoreOperateIcon,
      defaultMengli,
      emptyImg,
      itemWidth: 200,
      isInit: true,
      memeOptions: JSON.parse(JSON.stringify(memeOptions)),
      loading: false,
      filterData: {},
      tableData: {},
      totalCount: null,
      page: 1,
      perPage: 20,
      isActive: false,
      paramsOptions: {
        sortName: 4,
        sortType: 0,
        keyword: ''
      },
      showFilterDialog: false,
      filterValues: [],
      realTimeFilter: false
    };
  },
  computed: {
    sortOptions() {
      return [
        { id: 4, name: '上架时间' },
        { id: 0, name: '赞赏次数' },
        { id: 1, name: '赞赏总额' },
        { id: 2, name: '下载量' },
        { id: 3, name: '发送量' }
      ];
    },
    displayData() {
      return [
        { data: this.totalCount.downloadNum, label: '总下载量', icon: icon1, isMoney: false },
        { data: this.totalCount.sendNum, label: '总发送量', icon: icon2, isMoney: false },
        { data: this.totalCount.rewardsNum, label: '总赞赏次数', icon: icon3, isMoney: false },
        { data: this.totalCount.rewardsAmount, label: '总赞赏金额', icon: icon4 },
        { data: this.totalCount.stickersNum, label: '表情包套数', icon: icon5, isMoney: false }
      ];
    }
  },
  created() {
    this.getOptionsIp();
    this.getMengliList(true);
  },
  beforeDestroy() {
    window.onresize = null;
  },
  methods: {
    hasRouteAuth,
    changeLevel() {
      this.isActive = !this.isActive;
    },
    async getMengliList(reset = false) {
      try {
        if (reset) this.page = 1;
        const params = JSON.parse(JSON.stringify(this.paramsOptions));
        params.page = this.page;
        params.perPage = this.perPage;
        if (params.time && params.time.length === 2) {
          params.beginTime = params.time[0];
          params.endTime = params.time[1];
        }
        this.loading = true;
        this.getTotal(params);
        const res = await getMengliList(params);
        this.loading = false;
        this.tableData = res.data;
        if (this.isInit) {
          this.$nextTick(() => {
            this.getItemWidth();
            window.onresize = () => {
              return (() => {
                this.getItemWidth();
              })();
            };
          });
        }
        this.isInit = false;
      } catch (error) {
        console.log(error);
        this.loading = false;
        this.isInit = false;
      }
    },
    async getTotal(params) {
      try {
        const res = await getMengliListTotal(params);
        if (res.data) {
          this.totalCount = res.data;
        }
      } catch (error) {
        console.log(error);
      }
    },
    async getOptionsIp() {
      try {
        const res = await getOptionsIp();
        const item = {
          name: 'IP名称',
          label: 'ip', // 对应字段
          type: 'checkbox', // radio
          value: []
        };
        item.value = res.data;
        this.memeOptions.unshift(item);
      } catch (error) {
        console.log(error);
      }
    },
    changeSortNum(type) {
      this.$set(this.paramsOptions, 'sortType', type);
      this.getMengliList(true);
    },
    resetFilter() {
      const keys = this.memeOptions.map(item => item.label);
      keys.forEach(key => {
        delete this.paramsOptions[key];
      });
      this.paramsOptions.keyword = '';
      this.getMengliList(true);
    },
    handleFilterItemChange(obj) {
      Object.assign(this.paramsOptions, obj);
      this.realTimeFilter && this.getMengliList(true);
    },
    postMessage(obj) {
      Object.assign(this.paramsOptions, obj);
      // 验证参数完整
      this.getMengliList(true);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.getMengliList(true);
    },
    handleCurrentChange(page) {
      this.page = page;
      this.getMengliList();
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    changeSort(item, isMobile) {
      if (isMobile && item.id === this.paramsOptions.sortName) {
        this.$set(this.paramsOptions, 'sortType', this.paramsOptions.sortType === 1 ? 0 : 1);
      } else if (isMobile) {
        this.$set(this.paramsOptions, 'sortType', 1);
      }
      this.$set(this.paramsOptions, 'sortName', item.id);
      this.getMengliList(true);
    },
    goDetail(item, list) {
      if (item.ipId) {
        const routeUrl = this.$router.resolve({
          name: 'mengliDetail',
          params: { id: item.ipId },
          query: { workId: item.id }
        });
        window.open(routeUrl.href, '_blank');
      } else {
        ElMessage.warning('该表情包尚未关联IP，请先到IP编辑中关联');
      }
    },
    goCreate() {
      this.$router.push({
        name: 'mengliCreate'
      });
    },
    toLinkIp(item) {
      this.$router.push({
        name: 'mengliCreate',
        query: { createType: '1' }
      });
    },
    getItemWidth() {
      try {
        const biaoqing = document.getElementById('list-ul');
        if (!biaoqing) return;
        const wi = this.showMobilePage ? 153 : 216;
        const num = Math.round(biaoqing.clientWidth / wi);
        let itemWidth = biaoqing.clientWidth / num - 16;
        if (itemWidth > 210) {
          itemWidth = 210;
        }
        this.itemWidth = itemWidth;
      } catch (error) {
        console.log(error);
        this.itemWidth = 200;
      }
    },
    switchExpend(item) {
      this.$set(item, 'expend', !item.expend);
    },
    resetFilterItem(key) {
      return !this.paramsOptions[key];
    },
    selectValue() {
      const filterArray = [];
      Object.keys(this.paramsOptions).forEach(key => {
        const optionsMatchData = this.memeOptions.filter(item => item.label === key)[0];
        if (!optionsMatchData) return;
        const tagValues = [];
        const tagItem = Object.create(null);
        if (key !== 'time') {
          this.paramsOptions[key].forEach(val => {
            const curParamsValue = optionsMatchData.value.filter(item => item.id === val);
            tagValues.push(curParamsValue[0].name);
          });
          tagItem.value = tagValues.join(',');
        } else {
          if (!this.paramsOptions[key]) return;
          const startTime = standardFormatTime(this.paramsOptions[key][0], 'YYYY/MM/DD');
          const endTime = standardFormatTime(this.paramsOptions[key][1], 'YYYY/MM/DD');
          tagItem.value = `${startTime}-${endTime}`;
        }
        tagItem.name = optionsMatchData.name;
        tagItem.key = optionsMatchData.label;
        tagItem.value && filterArray.push(tagItem);
      });
      return filterArray;
    },
    deleteTag(item, e) {
      e.stopPropagation();
      delete this.paramsOptions[item.key];
      this.getMengliList(true);
    }
  }
};
</script>
<style lang="scss" scoped>
.list-container{
  margin: 16px;
}
.filter-container{
  padding: 20px 20px 24px 20px;
  background-color: #fff;
}
.table-list {
  padding: 0px 12px 55px 12px;
  background-color: #fff;
  overflow: hidden;
  min-height: calc(100vh - 176px - 48px);
}
.list-ul {
  display: flex;
  flex-flow: row wrap;
  margin-top: 12px;
  padding-top: 6px;
  margin-bottom: 16px;
  .list-li {
    margin: 0 8px 16px 8px;
    width:188px;
    height:188px;
    background:rgba(255,255,255,1);
    border: 1px solid #DDDDDD;
    // box-shadow:1px 1px 8px 0px rgba(221,225,234,1);
    border-radius:8px;
    padding: 16px;
    cursor: pointer;
  }
  .list-img {
    margin: 0 auto;
    width: 120px;
    height: 120px;
    overflow: hidden;
    border-radius:8px;
    img {
      border-radius:8px;
      object-fit: cover;
      width: 100%;
      height: 100%;
      display: block;
    }
  }
  .list-keyword {
      text-align: center;
      font-size:16px;
      font-family:PingFangSC-Medium,PingFang SC;
      font-weight:500;
      color:rgba(51,51,51,1);
      height: 36px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 10px;
      // border-bottom: 1px dashed #EBEEFD;
      .text {
        white-space: nowrap;
        overflow: hidden;
        display: inline-block;
        text-overflow: ellipsis;
        max-width: 78%;
      }
    }
  .list-info {
    margin-top: 16px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    width: 100%;
    display: flex;
    align-items: center;
    font-size:14px;
    font-family:PingFangSC-Regular,PingFang SC;
    line-height:14px;
    font-weight:400;
  }
  .list-info-title {
    color:rgba(153,153,153,1);
  }
  .list-info-name {
    color:rgba(51,51,51,1);
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
}
.filter-tag-group {
  margin-top: 8px;
  margin-right: 8px;
  color: #333;
  background-color: #EFF3FB;
  border-radius: 2px;
  .input-value {
    max-width: 12em;
    display: inline-block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  ::v-deep .el-tag__close {
    color: #999;
  }
  ::v-deep .el-tag__close:hover {
    background-color: #ccc;
  }
}
.select-num-tip {
  color: #406EFF;
  cursor: pointer;
}
.title {
  font-size:14px;
  color: #999999;
}
.dropdown-sort {
  display: flex;
  align-items: center;
  font-size: 14px;
  &.active {
    .name {
      color: #406EFF;
    }
  }
  .dropdown-sort-container {
    display: flex;
    align-items: center;
  }
  .icon {
    margin: 0 0 0 6px;
    &.active {
      color: #406EFF;
    }
    &.left {
      margin-right: -3px;
    }
    &.right {
      margin-left: -3px;
    }
  }
}
.table-list-top {
  display: flex;
  // align-items: center;
  margin-bottom: 20px;
  .num {
    font-size:16px;
    font-family:PingFangSC-Regular,PingFang SC;
    font-weight:400;
    color:rgba(64,110,255,1);
    line-height:16px;
  }
  .opeator {
    display: flex;
    align-items: center;
  }
  .opeator-btn {
    height: 32px;
    font-size: 15px;
    padding: 7px 10px;
    .icon {
      font-size: 15px;
    }
  }
  .opeator-grount {
    display: flex;
    margin-left: 10px;
    height:32px;
    border-radius:4px;
    border:1px solid rgba(221,221,221,1);
    background: #F8F8F8;
    align-items: center;
    overflow: hidden;
    &-item {
      padding: 0 12px;
      height:100%;
      display: flex;
      align-items: center;
      background:#F8F8F8;
      border-radius:4px;
      font-size:14px;
      font-family:AlibabaPuHuiTi-Medium,AlibabaPuHuiTi;
      line-height:14px;
      cursor: pointer;
      color: #666666;
      &.active {
        font-weight:500;
        color:rgba(64,110,255,1);
        background: #FFFFFF;
        border-radius:4px;
        position: relative;
        box-shadow: 2px 0px 13px 0px #dde1ea;
      }
    }
  }
}
.mengli-container {
  & ::v-deep {
    .el-timeline {
      padding-left: 0 !important;
      .el-timeline-item__wrapper .el-timeline-item__timestamp.is-top {
          &::after {
          content: '';
          width: 16px;
          height: 16px;
          display: inline-block;
          position: absolute;
          top: 5px;
          left: 0px;
          background: url('../../assets/timeline.png') center no-repeat;
          background-size: 100% auto;
        }
      }
    }
  }
}
.empty-container {
  margin: 0 auto;
  img {
    width: 120px;
    margin: 100px auto 0;
    display: block;
  }
  .empty-text {
    color: #666;
    font-size: 14px;
    text-align: center;
  }
}
.opeator-grount-item {
  .sort-container {
    display: inline-flex;
    flex-direction: column;
    align-items: center;
    height: 34px;
    width: 20px;
    vertical-align: middle;
    cursor: pointer;
    overflow: initial;
    position: relative;
    .sort-caret {
        width: 0;
        height: 0;
        border: 5px solid transparent;
        position: absolute;
        left: 7px;
      &.ascending {
        border-bottom-color: #999999;
        top: 6px;
      }
      &.descending {
        border-top-color: #999999;
        bottom: 5px;
      }
      &.active {
        &.ascending {
          border-bottom-color: #406EFF;
        }
        &.descending {
          border-top-color: #406EFF;
        }
      }
    }
  }
}
.hideItem {
  height: 206px;
  overflow: hidden;
}

.time-wrap-item {
  display: flex;
  align-items: center;
  .label {
    color: #333333;
    font-size: 16px;
    font-weight: 550;
    margin-right: 16px;
    margin-left: 8px;
    white-space: nowrap;
  }
  .flex {
    flex: 1;
  }
  .expend-btn {
    text-align: center;
    font-size: 16px;
    cursor: pointer;
    display: flex;
    align-items: center;
    color: #406EFF;
    margin-left: 16px;
    white-space: nowrap;
    &:hover {
      color: #2c5af1;
    }
  }
  .ip-name {
    display: flex;
    white-space: nowrap;
    align-items: center;
    font-size: 16px;
    color:#333;
    cursor: pointer;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  .ip-name-btn {
    cursor: pointer;
    font-size: 16px;
    color: #406EFF;
  }
}
.high-lv {
  cursor: pointer;
  flex-shrink: 0;
  margin-left: 10px;
  display: flex;
  align-items: center;
  img {
    width: 16px;
    margin-right: 3px;
  }
}
.list-container{
  &.is-mobile {
    margin: 0;
    padding: 0 !important;
    .filter-container {
      padding: 12px 0 12px 0 !important;
    }
    .mobile-data {
      margin-bottom: 0 !important;
    }
    .hideItem {
      height: 110px;
    }
    .table-list {
      padding: 0px 8px 55px 8px;
    }
    .list-ul {
      .list-li {
        padding: 4px 0 0 0;
        width: 100px;
        height: 100px;
        margin: 0 4px 16px 4px;
      }
      .list-img {
        width: 60px;
        height: 60px;
      }
      .list-keyword {
        height: 22px;
        line-height: 22px;
      }
    }
  }
}
.mobile-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 24px;
  .text {
    font-size: 10px;
    font-family: PingFang SC, PingFang SC-Regular;
    font-weight: 400;
    color: #aeb6c7;
    line-height: 14px;
    margin-top: 2px;
  }
  .img{
    width: 24px;
    height: 24px;
    img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
